package com.rambo.sad;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Create by Rambo on 2017/1/9
 * 2017.06.07 改进：去除初始化参数 freesevice 配置，请求路径中添加 freesevice 即可
 **/
public class SimpleAuthFilter implements Filter {
    private static Log logger = LogFactory.getLog(SimpleAuthFilter.class);

    private String defaultPage;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.defaultPage = filterConfig.getInitParameter("defaultPage");
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession(false);
        logger.info("reqUrl:" + request.getRequestURI());

        if (request.getRequestURI().contains("freeservice")) {
            filterChain.doFilter(request, response);
            return;
        }

        if (session != null && session.getAttribute("user") != null) {
            filterChain.doFilter(request, response);
            return;
        }

        request.setAttribute("SESSIONFILTER_MSG", "LOGIN_TIMEOUT");
        request.getRequestDispatcher(defaultPage).forward(servletRequest, servletResponse);
        logger.info("reqUrl：" + request.getRequestURI() + ";dispatchUrl:" + defaultPage);
    }

    public void destroy() {
        this.defaultPage = null;
    }
}